package event

import (
	"beergo/app/admin/models"
	sys "beergo/app/sys/models"
	"beergo/lib/event"
	"github.com/beego/beego/v2/server/web/context"
	"reflect"
)

func init() {
	Sync()
}

func Sync()  {
	event.ListenJoin("admin.AfterAdminUserCreate admin.AfterAdminUserUpdate", func(v interface{}, ctx *context.Context) {
		model,ok:=v.(*models.AdminUser)
		if ok {
			//更新数据的同时，更新User
			var userBind *sys.User
			if model.Uid == 0 {
				userBind = new(sys.User)
			}else {
				rep:=sys.UserRepository{}
				find := rep.Find(model.Uid)
				if find.Id == 0 {
					userBind = new(sys.User)
				}else {
					userBind = &find
				}
			}
			//更新数据
			userBind.Account = model.Account
			userBind.Phone = model.Account
			userBind.Nickname = model.Name
			userBind.Password = model.Password
			_,err:=userBind.Save()
			//todo 全局错误日志
			if err != nil {
				println(err.Error())
			}
			model.Uid = userBind.Id
			model.SetEventOff()
			_,err=model.Save()
			if err != nil {
				println("step1",err.Error())
			}
		}else {
			println(reflect.TypeOf(v).String())
		}
	})
}